package cn.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.util.Map;

public class JacksonUtil {
    public static Map<String, Object> parseXml(String xml) throws Exception {
        if(xml == null || xml.length() <= 0)
            return null;
        XmlMapper mapper = new XmlMapper();
        return mapper.readValue(xml, new TypeReference<Map<String, Object>>() {
        });
    }
    
    public static Map<String, Object> parseJson(String json) throws Exception {
        if (json == null || json.length() <= 0)
            return null;
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(json, new TypeReference<Map<String, Object>>() {
        });
    }
    
    public static String toXml(Object data) throws Exception {
        JacksonXmlModule module = new JacksonXmlModule();
        module.setDefaultUseWrapper(false);
        XmlMapper mapper = new XmlMapper(module);
        return mapper.writeValueAsString(data);
    }


    public static String toJson(Object result) throws Exception {
        if (result == null)
            return null;
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(result);
    }
//    public static CommonBean parseJsonBean(String json) throws Exception {
//        if (json == null || json.length() <= 0)
//            return new CommonBean();
//        return new CommonBean(parseJson(json));
//    }
}